require.async([ 'JqueryBase','PageUtil','CartUtil','ValidityNumberEnum','CarTypeEnum' ], function(window) {
	var cityCode = CookieUtil.get(Constant.CITY_CODE);
	if(!cityCode) {
		layer.alert("定位城市失败，请刷新后重试！");
		return;
	}
	
	var keyword = decodeURI(UrlUtil.getUrlParam('keyword'));
	var balance = -1;
	if (hasCustomerRole) {
		balance = BaseUtil.getData('crm/pointAccount/getPointAccountBalance');
	}
	initMenu();
	switch (UrlUtil.getUrlParam('location')) {
		case 'serve':
			initServe();
			$("#mylocation").html('<a href="'+basePath+'/index.html">首页</a> > <a href="javascript:location.reload()">洗车服务</a>');
			break;
		case 'point':
			initCoupon(false);
			initGoods(false);
			$("#mylocation").html('<a href="'+basePath+'/index.html">首页</a> > <a href="javascript:location.reload()">积分商城</a>');
			break;
		case 'coupon':
			initCoupon(true);
			$("#mylocation").html('<a href="'+basePath+'/index.html">首页</a> > <a href="'+basePath+'/search/searchlist.html?location=point">积分商城</a> > <a href="javascript:location.reload()">优惠券专区</a>');
			break;
		case 'goods':
			initGoods(true);
			$("#mylocation").html('<a href="'+basePath+'/index.html">首页</a> > <a href="'+basePath+'/search/searchlist.html?location=point">积分商城</a> > <a href="javascript:location.reload()">超值礼品</a>');
			break;
		case 'recharge':
			initRecharge();
			$("#mylocation").html('<a href="'+basePath+'/index.html">首页</a> > <a href="javascript:location.reload()">优惠充值</a>');
			break;
		case 'wash':
			initWash();
			$("#mylocation").html('<a href="'+basePath+'/index.html">首页</a> > <a href="javascript:location.reload()">洗车卡</a>');
			break;
		default:
			initServe();
			initCoupon(true);
			initGoods(true);
			initRecharge();
			initTuijian();
			$("#tuijian-ul-div").show();
			$("#mylocation").html('<a href="'+basePath+'/index.html">首页</a> > <a href="javascript:location.reload()">搜索结果</a>');
			break;
	}
	/** *************** 功能菜单 ********************** */
	function initMenu(){
		var templete = '<div class="left"> <a href="{basePath}/{url}"> <p>{text}</p> </a> </div>',
		menus = {'环保洗车':'search/searchlist.html?location=serve',
			'优惠充值':'search/searchlist.html?location=recharge',
			'积分商城':'search/searchlist.html?location=point',
			'购物车':'point/auth/cart.html',
			'车险频道':'javascript:;',
			'违章查询':'javascript:;',
			'APP下载':'app/download.html',
			'我要加盟':'javascript:;',
			'关于我们':'javascript:;',
			'洗车卡':'search/searchlist.html?location=wash',
			'超值礼品':'search/searchlist.html?location=goods',
			'优惠券专区':'search/searchlist.html?location=coupon',
			'我的账户':'user/auth/usercenter.html',
			'洗车服务订单':'user/auth/myorder.html',
			'积分兑换订单':'user/auth/myorder.html',
			'我的消息':'user/auth/message.html',
			'我的优惠券':'coupon/auth/mycoupon.html',
			'个人资料':'user/auth/personalinfo.html',
			'账户安全':'user/auth/countsafe.html'},html = [];
		if(keyword){
			for (var key in menus) {
				if(key.indexOf(keyword)!=-1){
					html.push(templete.replaceAll('{basePath}',basePath).replaceAll('{url}',menus[key]).replaceAll('{text}',key));
				}
			}
		}
		if (html.length > 0) {
			$('.serviceitem').html(html.join(''));
			$('#mutli-box').show();
		}
	}
	/** *************** 洗车服务 ********************** */
	function initServe(){
		window.servePage = function(pageindex) {
			var limit = 4,templete = '<li class="clearfix"><div class="proimg left"><img onclick="{onck}" style="width:175px;height:100px;" src="{imgPath}" /></div><div class="txt left"><span class="name">{servName}</span><span class="price">价格：{price} 元</span><span class="name">评价：{levels}</span></div><div class=" right"><a href="{url}"class="a_btn">我要预约</a></div></li>'; 
			BaseUtil.get('search/front/pageServe', function(result) {
				var html = [];
				if (result.items.length > 0) {
					$.each(result.items,function(idx,item){
						var levels = '';
						if(item.evaluateRate){
							var evaluateRate = item.evaluateRate; 
							var len = 0; 
							if(evaluateRate >= 0.8) len = 5;
							else if(evaluateRate >= 0.6) len = 4; 
							else if(evaluateRate >= 0.4) len = 3;
							else if(evaluateRate >= 0.2) len = 2;
							else len = 1; 
							for(var i = 0; i < 5;i++){ 
								if(i <= len){
									levels += '<img style="width:20px;height:20px;margin-top: 5px;" src="'+basePath+'/front/images/sxx.png" />';
								} else {
									levels += '<img style="width:20px;height:20px;margin-top: 5px;" src="'+basePath+'/front/images/kxx.png" />';
								}
							}
						} else { 
							levels = '<img style="width:20px;height:20px;margin-top: 5px;" src="'+basePath+'/front/images/kxx.png" /><img style="width:20px;height:20px;margin-top: 5px;" src="'+basePath+'/front/images/kxx.png" /><img style="width:20px;height:20px;margin-top: 5px;" src="'+basePath+'/front/images/kxx.png" /><img style="width:20px;height:20px;margin-top: 5px;" src="'+basePath+'/front/images/kxx.png" /><img style="width:20px;height:20px;margin-top: 5px;" src="'+basePath+'/front/images/kxx.png" />';
						}
						html.push(templete.replaceAll("{basePath}",basePath).replaceAll("{servName}",item.serveName).replaceAll("{price}",NumberUtil.roundString(item.servicePrice)).replaceAll("{imgPath}",basePath+"/file/display/"+item.thumbnailUrl).replaceAll("{url}",basePath+"/serve/servicebespeak.html?id="+item.id)
								.replaceAll("{onck}","location.href='"+basePath+"/serve/servicebespeak.html?id="+item.id+"&_='")
								.replaceAll("{levels}",levels)
						); 
					});
					$("#servePage").html(PageUtil.getHtml(result.total, pageindex, 5, limit,'servePage'));
					$("#serve-ul").html(html.join(''));   
					$("#serve-ul-div").show();
				}
			}, {
				'baiduCode' : cityCode,
				'serveName' : keyword,
				'start' : (pageindex - 1) * limit,
				'limit' : limit
			});
		}
		servePage(1);
	}
	/**********************洗车卡******************************/
	function initWash(){
		$('#selectBox').show();
		$(".car_a").click(function(){
			$('.car_a').removeClass('cur');
			$(this).addClass('cur');
			initEstate($("#countySelect option:selected").val());
		});
		window.alertServes = function(msg){
			layer.alert(msg,{
				title:'洗车卡详情'
			});
		}
		window.washPage = function(pageindex,estateId) {
			var limit = 8,templete = '<li> <div class="yhq_img"> <div class="title">{washCardName}</div> <div class="">{sellPrice} 元</div> </div> <div class="yhq_txt"> <p>包含项目：<a style="cursor: pointer;text-decoration: underline;color: #f98322;" href="{servesfunc}">{serves}</a></p> <p>有效时间：{validityNumber}</p><p>适用车型：{cartype}</p> <a class="btn_a" href="{func}">立即购买</a> </div> </li>'; 
			BaseUtil.get('search/front/pageWashCardType', function(result) {
				if (result.items.length > 0) {
					var html = [];
					$.each(result.items,function(idx,item){
						var serves = [],serveList = item.serveList;
						for (var i = 0; i < serveList.length; i++) {
							var se = serveList[i];
							serves.push(se.serveName+'*'+se.userNum);
						}
						var serveStr = serves.join(','),newServeStr;
						if(serveStr.length > 15){
							newServeStr = serveStr.substring(0,13)+'...';
						}
						html.push(templete.replaceAll('{washCardName}',item.washCardName)
						.replaceAll('{sellPrice}',NumberUtil.roundString(item.sellPrice))
						.replaceAll('{serves}',newServeStr||serveStr)
						.replaceAll('{cartype}',CarTypeEnum.getHtml(item.serveStandardType))
						.replaceAll('{servesfunc}','javascript:alertServes(\''+serveStr+'\');')
						.replaceAll('{validityNumber}',ValidityNumberEnum.getHtml(item.validityNumber))
						.replaceAll('{func}','javascript:CartUtil.wash('+item.id+',\''+item.washCardName+'\',\''+NumberUtil.roundString(item.sellPrice)+'\')'));
					});
					$("#washPage").html(PageUtil.getHtml(result.total, pageindex, 5, limit,'washPage'));
					$("#washdiv").html('<ul>'+html.join('')+'</ul>');   
					$("#washPage").show();
					$("#wash-ul-div").show();
					return;
				}
				$("#wash-ul-div").show();
				$("#washdiv").show();
				$("#washdiv").html('<h3 style="text-align:center;">该小区暂无此规格洗车卡在售。</h3>');   
				$("#washPage").hide();
			}, {
				'washCardName' : keyword,
				'start' : (pageindex - 1) * limit,
				'limit' : limit,
				'estateId' : estateId,
				'serveStandardType' : $('.cur').attr('typeid')
			});
		}
		
		BaseUtil.get("eb/area/front/pageArea",function(result){
			var areaData = result.data,cityCode = CookieUtil.get(Constant.CITY_CODE);
			$.each(areaData.items,function(idx,item){  
				$("#citySelect").append('<option cityId="'+item.cityId+'" value="'+item.id+'" '+(cityCode == item.id ? 'selected':'') +'>'+item.name+'</option>');
			});
			changeDistrict($("#citySelect option:selected").attr('cityId'));
		});
		
		function changeDistrict(cityId){
			BaseUtil.get("eb/area/front/pageArea",function(result){
				$("#countySelect option").remove();
				 var areaData = result.data;  
				 $.each(areaData.items,function(idx,item){
					 $("#countySelect").append('<option value="'+item.id+'" >'+item.areaName+'</option>');
				 });
				 initEstate($("#countySelect option:selected").val());
			 },{"id":0,"parentId":cityId}); 
		}
		
		$("#citySelect").change(function(){
			changeDistrict($(this).find('option:selected').attr('cityId'));
		});
		
		$("#countySelect").change(function(){
			initEstate($(this).val());
		});
		function initEstate(areaId){
			BaseUtil.get("im/estate/front/pageEstate",function(result){
				$("#estateSelect option").remove();
				var items = result.data.items;
				if(items){
					$.each(items,function(idx,item){
						$("#estateSelect").append("<option value="+item.id+">"+item.estateName+"</option>");
					});
				}
				if($("#estateSelect option").length==0){
					$('#estateSelect').append("<option value=''>此地区暂无服务点</option>");
					return;
				}
				var selectId = $("#estateSelect option:selected").val();
				if(selectId){
					washPage(1,selectId);
				}
			},{'areaId':areaId});  
		}
	}
	/** *************** 积分商城 ********************** */
	function initCoupon(isPage){
		window.couponPage = function(pageindex) {
			var limit = 8,templete = '<li> <div class="yhq_img"> <div class="title">{couponTypeName}</div> <div class="">{sellPrice} 积分</div> </div> <div class="yhq_txt"> <p>使用说明：{useExplain}</p> <p>有效期：{validityNumber}(天)</p><p>可抵扣：{price} 元</p>   <a class="btn_a {disCss}"  href="{func}">{disText}</a> </div> </li>'; 
			if(!isPage){
				limit = 4;
				$("#couponMore").show();
			}
			BaseUtil.get('search/front/pageCouponType', function(result) {
				var html = [];
				if (result.items.length > 0) {
					$.each(result.items,function(idx,item){
						var temp = templete.replaceAll('{couponTypeName}',item.couponTypeName)
						.replaceAll('{sellPrice}',item.sellPrice)
						.replaceAll('{price}',NumberUtil.roundString(item.price))
						.replaceAll('{useExplain}',item.useExplain)
						.replaceAll('{validityNumber}',item.validityNumber);
						if (balance > item.sellPrice||balance==-1) {
							html.push(temp.replaceAll('{disCss}','').replaceAll('{disText}','立即兑换').replaceAll('{func}','javascript:CartUtil.exchange('+item.id+')'));
						}else{
							html.push(temp.replaceAll('{disCss}','disCss').replaceAll('{disText}','积分不足').replaceAll('{func}','javascript:;'));
						}
					});
					if(isPage){
						$("#couponTypePage").html(PageUtil.getHtml(result.total, pageindex, 5, limit,'couponPage'));
					}
					$("#couponType-ul").html(html.join(''));   
					$("#couponType-ul-div").show();
				}
			}, {
				'couponTypeName' : keyword,
				'start' : (pageindex - 1) * limit,
				'limit' : limit
			});
		}
		couponPage(1);
	}
	function initGoods(isPage){
		window.goodsclick = function(id){
			location.href=basePath+'/point/scoredetail.html?id='+id;
		}
		window.goodsPage = function(pageindex) {
			var limit = 8,templete = '<li> <div class="imgbox" onclick="{liclick}"> <img src="{basePath}/file/display/{thumbnailUrl}"> </div> <div class="desc">{goodsName}</div> <div class="scores">{price} 积分</div> <div class="btns mt10 clearfix"> <a class="buy left {disCss}" href="{atonce}">{disText}</a> <a class="cart right" href="{addtocart}">加入购物车</a> </div> </li>'; 
			if(!isPage){
				limit = 4;
				$("#goodsMore").show();
			}
			BaseUtil.get('search/front/pageGoods', function(result) {
				var html = [];
				if (result.items.length > 0) {
					$.each(result.items,function(idx,item){
						var temp = templete.replaceAll('{thumbnailUrl}',item.thumbnailUrl)
						.replaceAll('{goodsName}',item.goodsName)
						.replaceAll('{price}',item.price)
						.replaceAll('{basePath}',basePath)
						.replaceAll('{addtocart}','javascript:CartUtil.addToCart('+item.id+');')
						.replaceAll('{liclick}','goodsclick('+item.id+')');
						if (balance > item.price||balance==-1) {
							html.push(temp.replaceAll('{disCss}','').replaceAll('{disText}','立即兑换').replaceAll('{atonce}','javascript:CartUtil.submit('+item.id+')'));
						}else{
							html.push(temp.replaceAll('{disCss}','disCss').replaceAll('{disText}','积分不足').replaceAll('{atonce}','javascript:;'));
						}
					});
					if(isPage){
						$("#goodsPage").html(PageUtil.getHtml(result.total, pageindex, 5, limit,'goodsPage'));
					}
					$("#goods-ul").html(html.join(''));   
					$("#goods-ul-div").show();
				}
			}, {
				'goodsName' : keyword,
				'start' : (pageindex - 1) * limit,
				'limit' : limit
			});
		}
		goodsPage(1);
	}
	/** *************** 优惠充值 ********************** */
	function initRecharge(){
		window.rechargePage = function(pageindex) {
			var limit = 8,templete = '<li> <div class="yhq_img"> <div class="title">{rechargeCardTypeName}</div> <div class="">售价：{sellPrice} 元</div> </div> <div class="yhq_txt"> <p>充值金额：{price} 元</p> <a class="btn_a" href="{func}">立即充值</a> </div> </li>'; 
			BaseUtil.get('search/front/pageRechargeCardType', function(result) {
				var html = [];
				if (result.items.length > 0) {
					$.each(result.items,function(idx,item){
						var sellPrice = NumberUtil.roundString(item.sellPrice); 
						html.push(templete.replaceAll('{rechargeCardTypeName}',item.rechargeCardTypeName)
						.replaceAll('{sellPrice}',sellPrice)
						.replaceAll('{price}',NumberUtil.roundString(item.price))
						.replaceAll('{func}','javascript:CartUtil.recharge('+item.id+',\''+item.rechargeCardTypeName+'\',\''+sellPrice+'\')'));
					});
					$("#rechargePage").html(PageUtil.getHtml(result.total, pageindex, 5, limit,'rechargePage'));
					$("#recharge-ul").html(html.join(''));   
					$("#recharge-ul-div").show();
				}
			}, {
				'rechargeCardTypeName' : keyword,
				'start' : (pageindex - 1) * limit,
				'limit' : limit
			});
		}
		rechargePage(1);
	}
	
	function initTuijian(){
		//获取服务
		BaseUtil.get('search/front/pageServe', function(result) {
			var html = [],templete = '<li class="clearfix"><div class="proimg left"><img style="width:175px;height:100px;" src="{imgPath}" /></div><div class="txt left"><span class="name">{servName}</span><span class="price">价格：{price} 元</span></div><div class=" right"><a href="{url}"class="a_btn">我要预约</a></div></li>';
			if (result.items.length > 0) { 
				$.each(result.items,function(idx,item){
					html.push(templete.replaceAll("{basePath}",basePath).replaceAll("{servName}",item.serveName).replaceAll("{price}",NumberUtil.roundString(item.servicePrice)).replaceAll("{imgPath}",basePath+"/file/display/"+item.thumbnailUrl).replaceAll("{url}",basePath+"/serve/servicebespeak.html?id="+item.id));
				});
			}else{
				html.push('未发布洗车服务')
			}
			$("#tuijian-serve-ul").html(html.join(''));   
		}, {
			'baiduCode' : cityCode,
			'start' : 0,
			'limit' : 2
		});
		//获取商品
		BaseUtil.get('search/front/pageGoods', function(result) {
			var html = [],templete = '<li> <div class="imgbox" onclick="{liclick}"> <img src="{basePath}/file/display/{thumbnailUrl}"> </div> <div class="desc">{goodsName}</div> <div class="scores">{price} 积分</div> <div class="btns mt10 clearfix"> <a class="buy left {disCss}" href="{atonce}">{disText}</a> <a class="cart right" href="{addtocart}">加入购物车</a> </div> </li>';
			if (result.items.length > 0) {
				$.each(result.items,function(idx,item){
					var temp = templete.replaceAll('{thumbnailUrl}',item.thumbnailUrl)
					.replaceAll('{goodsName}',item.goodsName)
					.replaceAll('{price}',item.price)
					.replaceAll('{basePath}',basePath)
					.replaceAll('{addtocart}','javascript:CartUtil.addToCart('+item.id+');')
					.replaceAll('{liclick}','goodsclick('+item.id+')');
					if (balance > item.price ||balance==-1) {
						html.push(temp.replaceAll('{disCss}','').replaceAll('{disText}','立即兑换').replaceAll('{atonce}','javascript:CartUtil.submit('+item.id+')'));
					}else{
						html.push(temp.replaceAll('{disCss}','disCss').replaceAll('{disText}','积分不足').replaceAll('{atonce}','javascript:;'));
					}
				});
			}else{
				html.push('未发布积分商品')
			}
			$("#tuijian-goods-ul").html(html.join(''));   
		}, {
			'start' : 0,
			'limit' : 4
		});
		//获取优惠券
		BaseUtil.get('search/front/pageCouponType', function(result) {
			var html = [],templete = '<li> <div class="yhq_img"> <div class="title">{couponTypeName}</div> <div class="">{sellPrice} 积分</div> </div> <div class="yhq_txt"> <p>使用说明：{useExplain}</p> <p>有效期：{validityNumber}(天)</p><p>可抵扣：{price} 元</p>   <a class="btn_a" href="{func}">立即兑换</a> </div> </li>';
			if (result.items.length > 0) {
				$.each(result.items,function(idx,item){
					html.push(templete.replaceAll('{couponTypeName}',item.couponTypeName)
					.replaceAll('{sellPrice}',NumberUtil.roundString(item.sellPrice))
					.replaceAll('{price}',NumberUtil.roundString(item.price))
					.replaceAll('{useExplain}',item.useExplain)
					.replaceAll('{validityNumber}',item.validityNumber)
					.replaceAll('{func}','javascript:CartUtil.exchange('+item.id+')'));
				});
			}else{
				html.push('未发布优惠券')
			}
			$("#tuijian-couponType-ul").html(html.join(''));   
		}, {
			'start' : 0,
			'limit' : 4
		});
	}
});
